'use strict';

const Service = require('egg').Service;

class EnterpriseService extends Service {
  // 获取企业列表
  async getEnterpriseList({ page = 1, pageSize = 10, keyword = '', status = '' }) {
    const { ctx } = this;
    
    console.log('获取企业列表，参数:', { page, pageSize, keyword, status });
    
    // 确保参数是数字类型
    const pageNum = parseInt(page, 10) || 1;
    const sizeNum = parseInt(pageSize, 10) || 10;
    
    console.log('转换后的参数:', { pageNum, sizeNum, keyword, status });
    
    const where = {};
    
    // 添加搜索条件 - 使用model定义的字段名（驼峰命名）
    if (keyword) {
      where.enterpriseName = {
        [ctx.app.Sequelize.Op.like]: `%${keyword}%`
      };
    }
    
    if (status) {
      where.status = status;
    }

    try {
      const { count, rows } = await ctx.model.Enterprise.findAndCountAll({
        where,
        order: [['createTime', 'DESC']], // 使用model字段名
        limit: sizeNum,
        offset: (pageNum - 1) * sizeNum,
        attributes: ['enterpriseId', 'enterpriseName', 'description', 'imageUrl', 'status', 'createTime', 'updateTime']
      });

      console.log('查询成功，找到', count, '条记录');

      // 转换数据为JSON格式
      const enterprises = rows.map(row => row.toJSON ? row.toJSON() : row);

      return {
        enterprises: enterprises || [],
        pagination: {
          total: count,
          page: pageNum,
          pageSize: sizeNum
        }
      };
    } catch (error) {
      console.error('查询企业列表失败:', error);
      throw error;
    }
  }

  // 删除企业
  async deleteEnterprise(enterpriseId) {
    const { ctx } = this;
    
    const enterprise = await ctx.model.Enterprise.findByPk(enterpriseId);
    if (!enterprise) {
      throw new Error('企业不存在');
    }

    // 检查是否有关联数据
    const jobCount = await ctx.model.Job.count({
      where: { enterpriseId }
    });

    const employeeCount = await ctx.model.Employee.count({
      where: { enterpriseId }
    });

    const reviewCount = await ctx.model.Review.count({
      where: { enterpriseId }
    });

    if (jobCount > 0 || employeeCount > 0 || reviewCount > 0) {
      throw new Error('该企业下还有关联数据，无法删除');
    }

    await enterprise.destroy();
    return true;
  }

  // 创建企业
  async createEnterprise(enterpriseData, logoFile, imageFile, userId) {
    const { ctx } = this;
    const fs = require('fs');
    const path = require('path');
    
    // 准备插入数据
    const enterpriseName = enterpriseData.enterpriseName || '';
    const description = enterpriseData.description || '';
    const benefits = enterpriseData.benefits || '';
    const status = enterpriseData.status || 'active';
    
    let logoUrl = '';
    let imageUrl = '';
    
    try {
      // 处理Logo上传
      if (logoFile) {
        const logoDir = path.join(ctx.app.baseDir, 'app/public/job/logo');
        if (!fs.existsSync(logoDir)) {
          fs.mkdirSync(logoDir, { recursive: true });
        }
        const logoExt = path.extname(logoFile.filename);
        const logoName = `${Date.now()}${logoExt}`;
        const logoPath = path.join(logoDir, logoName);
        fs.copyFileSync(logoFile.filepath, logoPath);
        logoUrl = `/public/job/logo/${logoName}`;
      }
      
      // 处理企业图片上传
      if (imageFile) {
        const imageDir = path.join(ctx.app.baseDir, 'app/public/job/image');
        if (!fs.existsSync(imageDir)) {
          fs.mkdirSync(imageDir, { recursive: true });
        }
        const imageExt = path.extname(imageFile.filename);
        const imageName = `${Date.now()}${imageExt}`;
        const imagePath = path.join(imageDir, imageName);
        fs.copyFileSync(imageFile.filepath, imagePath);
        imageUrl = `/public/job/image/${imageName}`;
      }
      
      // 优先使用logo，如果没有logo则使用image
      const finalImageUrl = logoUrl || imageUrl;
      
      // 使用Model方式创建企业（参考createJob的做法）
      const enterprise = await ctx.model.Enterprise.create({
        enterpriseName,
        description,
        imageUrl: finalImageUrl,
        benefits,
        status
      });
      
      const enterpriseId = enterprise.enterpriseId;
      
      // 更新用户角色为企业用户
      const user = await ctx.model.User.findByPk(userId);
      if (user) {
        await user.update({ role: 'enterprise' });
        
        // 创建员工记录
        await ctx.model.Employee.create({
          enterpriseId,
          employeeName: user.username || '管理员',
          phone: '',
          hireTime: new Date(),
          employeeStatus: 'active',
          position: '管理员',
          department: '管理部'
        });
      }
      
      // 转换为前端需要的格式
      const result = {
        enterpriseId: enterprise.enterpriseId,
        enterpriseName: enterprise.enterpriseName,
        description: enterprise.description || '',
        imageUrl: enterprise.imageUrl || '',
        benefits: enterprise.benefits || '',
        rating: parseFloat(enterprise.rating) || 0,
        status: enterprise.status,
        createTime: enterprise.createTime,
        updateTime: enterprise.updateTime
      };
      
      return result;
      
    } catch (error) {
      // 如果失败，删除已上传的文件
      if (logoFile && logoUrl) {
        const logoPath = path.join(ctx.app.baseDir, 'app/public/job/logo', path.basename(logoUrl));
        if (fs.existsSync(logoPath)) {
          fs.unlinkSync(logoPath);
        }
      }
      if (imageFile && imageUrl) {
        const imagePath = path.join(ctx.app.baseDir, 'app/public/job/image', path.basename(imageUrl));
        if (fs.existsSync(imagePath)) {
          fs.unlinkSync(imagePath);
        }
      }
      throw new Error(`创建企业失败: ${error.message}`);
    }
  }

  // 获取企业信息
  async getEnterpriseInfo(enterpriseId) {
    const { ctx } = this;
    
    const enterprise = await ctx.model.Enterprise.findByPk(enterpriseId, {
      include: [
        {
          model: ctx.model.Job,
          as: 'jobs',
          where: { jobStatus: 'active' },
          required: false
        },
        {
          model: ctx.model.Review,
          as: 'reviews',
          required: false
        }
      ]
    });

    if (!enterprise) {
      throw new Error('企业不存在');
    }

    // 计算统计数据
    const jobCount = await ctx.model.Job.count({
      where: { enterpriseId, jobStatus: 'active' }
    });

    const reviewCount = await ctx.model.Review.count({
      where: { enterpriseId }
    });

    const avgRating = await ctx.model.Review.findOne({
      where: { enterpriseId },
      attributes: [
        [ctx.app.Sequelize.fn('AVG', ctx.app.Sequelize.col('rating')), 'avgRating']
      ],
      raw: true
    });

    return {
      ...enterprise.toJSON(),
      jobCount,
      reviewCount,
      avgRating: avgRating.avgRating || 0
    };
  }

  // 更新企业信息
  async updateEnterpriseInfo(enterpriseId, updateData) {
    const { ctx } = this;
    
    const enterprise = await ctx.model.Enterprise.findByPk(enterpriseId);
    if (!enterprise) {
      throw new Error('企业不存在');
    }

    updateData.updateTime = new Date();
    await enterprise.update(updateData);
    
    return await this.getEnterpriseInfo(enterpriseId);
  }

  // 获取企业统计数据
  async getEnterpriseStatistics(enterpriseId) {
    const { ctx } = this;
    
    const jobCount = await ctx.model.Job.count({
      where: { enterpriseId }
    });

    const activeJobCount = await ctx.model.Job.count({
      where: { enterpriseId, jobStatus: 'active' }
    });

    const totalApplications = await ctx.model.JobApplication.count({
      include: [
        {
          model: ctx.model.Job,
          where: { enterpriseId }
        }
      ]
    });

    const reviewCount = await ctx.model.Review.count({
      where: { enterpriseId }
    });

    const avgRating = await ctx.model.Review.findOne({
      where: { enterpriseId },
      attributes: [
        [ctx.app.Sequelize.fn('AVG', ctx.app.Sequelize.col('rating')), 'avgRating']
      ],
      raw: true
    });

    return {
      totalJobs: jobCount,
      activeJobs: activeJobCount,
      totalApplications,
      reviewCount,
      avgRating: avgRating.avgRating || 0
    };
  }

  // 获取企业评价列表
  async getEnterpriseReviews(enterpriseId, { page, pageSize }) {
    const { ctx } = this;
    
    // 确保分页参数为数字类型
    const pageNum = parseInt(page, 10) || 1;
    const pageSizeNum = parseInt(pageSize, 10) || 10;
    
    console.log('获取企业评价列表（EnterpriseService），参数:', { enterpriseId, pageNum, pageSizeNum });
    
    const { count, rows } = await ctx.model.Review.findAndCountAll({
      where: { enterpriseId: Number(enterpriseId) },
      order: [['reviewTime', 'DESC']],
      limit: pageSizeNum,
      offset: (pageNum - 1) * pageSizeNum
    });

    console.log('查询结果（EnterpriseService）:', { count, rowsCount: rows.length });

    return {
      list: rows,
      total: count,
      page: pageNum,
      pageSize: pageSizeNum
    };
  }

  // 回复企业评价
  async replyEnterpriseReview(reviewId, replyContent) {
    const { ctx } = this;
    
    const review = await ctx.model.Review.findByPk(reviewId);
    if (!review) {
      throw new Error('评价不存在');
    }

    await review.update({
      replyContent,
      replyTime: new Date()
    });

    return review;
  }

  // 处理企业投诉
  async processEnterpriseComplaint(complaintId, processData) {
    const { ctx } = this;
    
    const review = await ctx.model.Review.findByPk(complaintId);
    if (!review) {
      throw new Error('投诉不存在');
    }

    await review.update({
      complaintStatus: processData.processResult,
      replyContent: processData.processNote,
      replyTime: new Date()
    });

    return review;
  }
}

module.exports = EnterpriseService;
